<template>
  <div class="addDialg">
    <el-dialog
      :close-on-click-modal="false"
      :title="titleName"
      :visible.sync="dialogTableVisible"
      width="85%">
      <div class="pageTop">
        <el-form :rules="rules" :model="addDialgData" ref="addDialgData" :inline="true" class="inputWidth"  style="padding: 0px 10px; padding-top: 20px;"  label-width="80px">
          <el-form-item label="盘点仓库" prop="warehouseId">
            <el-select
              v-model="addDialgData.warehouseId"
              placeholder="请选择"
              @change="pandianckChange"
              clearable
              size="medium">
              <el-option
                v-for="item in camgkuList"
                :key="item.warehouseId"
                :label="item.warehouseName"
                :value="item.warehouseId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="单据日期" prop="crtTime">
            <el-date-picker
              size="medium"
              v-model="addDialgData.crtTime"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="零库存" label-width="80px" >
            <el-select
              v-model="addDialgData.zeroType"
              placeholder="请选择"
              clearable
              size="medium">
              <el-option
                v-for=" item in lkcsList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="盘点单号：" label-width="100px">
            {{addDialgData.inventoryLossCode}}
          </el-form-item>
          <el-form-item label="扫码录入" label-width="80px" >
            <input class="inputClass" v-model="saomaCode" type="text"  placeholder="单行输入"    v-on:keyup.enter="submit()" >
          </el-form-item>
          <el-form-item label="产品分类" >
            <el-button type="success"  size="medium" @click="handleIconClickDh">请选择产品分类</el-button>
          </el-form-item>


          <el-form-item label="备注" >
            <el-input  maxlength="250" show-word-limit size="medium" v-model="addDialgData.remark" placeholder="请输入备注"></el-input>
          </el-form-item>
          <el-form-item label="" >
            <el-button type="primary" icon="el-icon-upload2"  size="medium" @click="handleImport">批量导入</el-button>
          </el-form-item>

        </el-form>
      </div>
      <el-table  height="350" v-loading="loading" :data="addDialgData.inventoryLossInfoList" stripe border style="margin-top: 20px" :header-cell-style="{background:'#eef1f6',color:'#606266'}">
        <el-table-column align="center" label="序号" type="index" width="50"></el-table-column>
        <el-table-column align="center" label="商品"   property="goodsName" show-overflow-tooltip > </el-table-column>
        <el-table-column align="center" label="商品编号"   property="goodsId"></el-table-column>
        <el-table-column align="center" label="商品编码"   property="goodsSn"></el-table-column>
        <el-table-column align="center" label="单位"   property="goodsUnit"></el-table-column>
        <el-table-column align="center" label="产品分类"   property="catName"></el-table-column>
        <el-table-column align="center" label="盘点数量"   property="atPresentCount">
          <template slot-scope="scope">
            <el-input @change="changeSL" onkeyup="value=value.replace(/[^\d]+/g,'')"  v-show="scope.row.goodsId" v-model="scope.row.atPresentCount" type="text" placeholder=""></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="系统库存"   property="inventory"></el-table-column>
        <el-table-column align="center" label="盈亏数"   property="">
          <template slot-scope="scope">
            {{scope.row.atPresentCount*1-scope.row.inventory*1}}
          </template>
        </el-table-column>
        <el-table-column align="center" label="成本单价"   property="price"></el-table-column>
        <el-table-column align="center" label="盈亏成本"   property="">
          <template slot-scope="scope">
            {{  Math.round ((scope.row.atPresentCount*1-scope.row.inventory*1)*(scope.row.price*1)*100 )/ 100  }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="备注"   property="remark" width="200">
          <template slot-scope="scope">
            <el-input maxlength="250" show-word-limit v-show="scope.row.goodsId" v-model="scope.row.remark"  placeholder="这里写备注"></el-input>
          </template>
        </el-table-column>


        <el-table-column align="center" label="管理" width="150">
          <template slot-scope="scope">
            <el-button size="mini" type="danger"   @click="handleDelete(scope.$index, scope.row)">删除</el-button>
<!--            <el-button size="mini" type="primary"   @click="addBtn">添加</el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <div style="height: 50px;line-height: 50px;">
        <span style="margin-left: 50px"><b>合计：</b> </span>
        <span style="margin-left: 20px">盘点数量：{{addDialgData.inventoryLossCount}}</span>
      </div>
      <div class="pageTop">
        <el-form :model="addDialgData" ref="addDialgData" :inline="true" class="inputWidth"  style="padding: 0px 10px; padding-top: 20px;" label-width="100px" >
          <el-form-item label="入库人：">
            {{yunyingName}}
          </el-form-item>
          <el-form-item label="下单时间：" v-show="addData.leixing=='put'">
            {{addDialgData.crtTime}}
          </el-form-item>
          <el-form-item label="审核人：" v-show="addData.leixing=='put'">
            {{addDialgData.auditUserName}}
          </el-form-item>
          <el-form-item label="审核时间：" v-show="addData.leixing=='put'">
            {{addDialgData.auditTime}}
          </el-form-item>
          <el-form-item label="审核状态：" v-show="addData.leixing=='put'">
            <span v-show="zhuangtai==2" style="color: red">未审核</span>
            <span v-show="zhuangtai==3" style="color: red">已审核</span>
            <span v-show="zhuangtai==4" style="color: red">驳回</span>
          </el-form-item>
          <el-form-item label="" style="float: right">
            <el-button  v-if="auditQX==1"  type="primary" size="medium" @click="shBtn" v-show="addData.leixing=='put' && zhuangtai==2 ||zhuangtai==4 " >审核</el-button>
            <el-button  v-if="auditQX==1" type="primary" size="medium" @click="fsBtn" v-show="addData.leixing=='put' && zhuangtai==3 ">反审</el-button>
            <el-button  v-if="addQX==1" type="success"  size="medium" @click="saveBtn" v-show="addData.leixing=='post' || zhuangtai==2 ||zhuangtai==4">保存</el-button>
<!--            <el-button type="danger" size="medium" @click="delBtn" v-show="addData.leixing=='put'">删除</el-button>-->
          </el-form-item>
        </el-form>
      </div>

    </el-dialog>
    <shangpin-Dialog v-if="shangpinShow" :shnagpinData="shnagpinData" @callback="callback"></shangpin-Dialog>
    <daoru-Dialog v-if="daoruShow" :daoruData="daoruData"  @daoruback="daoruback"></daoru-Dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import {DeleteJL,focusXL,selectCG,getnewDat,deteleObject} from "@/utils/index"
import shangpinDialog from '../../components/pdspDialog'
import daoruDialog from '../../components/daoruDialog'

export default {
  props: ['addData'],
  name: "Role",
  components:{
    shangpinDialog,
    daoruDialog
  },
  data() {
    return {
      deleteQX:localStorage.getItem("delete"),//删除权限
      addQX:localStorage.getItem("add"),//保存权限
      auditQX:localStorage.getItem("audit"),//审核权限
      daoruShow:false,
      daoruData:{},
      zhuangtai:2,
      saomaCode:'',//扫码录入
      //零库存
      lkcsList:[
        {value:"0",label:'包含'},
        {value:"1",label:'不包含'},
      ],
      cgdData:{},
      cgdShow:false,
      //仓库数据
      camgkuList:[],
      restaurantsb:[],
      // 表单校验
      rules: {
        warehouseId: [
          { required: true, message: "入库仓库不能为空", trigger: "blur" }
        ],
        catType: [
          { required: true, message: "采购计划不能为空", trigger: "blur" }
        ],
        crtTime: [
          { required: true, message: "单据日期不能为空", trigger: "blur" }
        ],
      },
      yunyingName:localStorage.getItem("loginUserName"),

      //调拨日期
      dbDateList:[],
      shnagpinData:{},
      shangpinShow:false,
      xiabiao:0,
      restaurants: [],
      leixing:'post',
      titleName:'新增盘点单',
      loading:false,
      //初始数据
      addDialgData: {
        warehouseId:'',//入库仓库
        crtTime:'',//单据日期
        inventoryLossCode:'',//单据编号
        catType:'',//产品分类
        remark:'',//备注
        zeroType:'0',
        inventoryLossCount:0,//盘点总数
        inventoryLossInfoList:[],
      },
      //记录数据
      modifyData:{
        inventoryLossCode:'',
        inventoryLossInfoList:[],
      },
      //单据日期
      djDateList:[],
      //付款日期
      fkDateList:[],
      dialogTableVisible:true,
      //调入仓库
      drList:[
        {value:'1',label:'调入仓库1'},
        {value:'2',label:'调入仓库2'},
        {value:'3',label:'调入仓库3'},
      ],
      //仓库
      cksList:[
        {value:'1',label:'仓库1'},
        {value:'2',label:'仓库2'},
        {value:'3',label:'仓库3'},
      ],
    };
  },

  watch: {
    dialogTableVisible: function () {
      this.dialogTableVisible = true;//始终让他为true;
      this.cancel();//隐藏
    },
  },
  created() {
    console.log('接受',this.addData)
    this.zhuangtai = this.addData.purchasePlanStatus
    this.getcangku()//仓库
    this.addDialgData.inventoryLossCode ='PDD'+Date.parse(new Date())/1000;
    this.getshangpin()
    var arr =  getnewDat()
    this.addDialgData.crtTime = arr[0]
    if(this.addData.leixing=='put'){
      this.titleName = '修改盘点单'
      //页面回显数据
      this.gethuixian()
    }
  },
  mounted() {

  },
  methods: {
    //批量导入
    handleImport:function (){
      console.log('批量导入')
      if(!this.addDialgData.warehouseId){
        this.$message({
          type: 'warning',
          message:'盘点仓库不能为空！'
        });
        return
      }
      var obj={}
      obj.warehouseId = this.addDialgData.warehouseId
      this.daoruData = obj

      this.daoruShow = true

    },
    //导入回调函数
    daoruback:function (msg){
      this.daoruShow = false
      if(msg){
        this.addDialgData.inventoryLossInfoList=msg
        this.jisuanshuliang(this.addDialgData.inventoryLossInfoList)
      }
    },
    //盘点仓库监听事件
    pandianckChange:function (){

      this.addDialgData.inventoryLossInfoList=[]
    },
    //键盘回车事件
    submit:function (){
      if(!this.saomaCode){
        this.$message({
          type: 'warning',
          message:'编码不能为空！'
        });
        return
      }
      this.loading = true
      request({
        url: '/wh/products/getById/'+this.saomaCode,
        method: 'get',
      }).then(response => {
        this.loading = false
        //判断是否有重复商品 如果有累加盘点数量
        console.log('response.data',response.data)
        var woaini = false
        for (var i=0;i<this.addDialgData.inventoryLossInfoList.length;i++){
          if(response.data[0].goodsId==this.addDialgData.inventoryLossInfoList[i].goodsId){
            this.addDialgData.inventoryLossInfoList[i].atPresentCount++
            woaini = true
          }
        }
        if(!woaini){
          this.$message({
            type: 'warning',
            message:'没有找到对应的商品！'
          });
        }

        this.jisuanshuliang(this.addDialgData.inventoryLossInfoList)
      });
    },
    //数量监听
    changeSL:function (){
      console.log('监听',this.addDialgData.inventoryLossInfoList)
      this.jisuanshuliang(this.addDialgData.inventoryLossInfoList)

    },

    //采购单号点击
    handleIconClickDh(ev) {


      if(!this.addDialgData.warehouseId){
        this.$message({
          type: 'warning',
          message:'请选择盘点仓库！'
        });
        return
      }
      var obj = {}
      obj.arr = this.addDialgData.inventoryLossInfoList
      obj.warehouseId = this.addDialgData.warehouseId
      obj.zeroType = this.addDialgData.zeroType
      this.shnagpinData = obj
      console.log('点击',ev);
      this.shangpinShow = true
    },
    //获取回显数据
    gethuixian:function (){
      this.loading = true
      request({
        url: '/wh/inventoryLoss/getById/'+this.addData.id,
        method: 'get',
      }).then(response => {
        this.loading = false
        if(response.code==200){
          this.addDialgData = response.data
          this.jisuanshuliang(this.addDialgData.inventoryLossInfoList)
        }else {
          this.$message({
            type: 'warning',
            message:response.msg
          });
        }

      });
    },
    //获取仓库
    getcangku:function (){
      request({
        url: '/wh/warehouse/getFinishedProducts',
        method: 'get',
      }).then(response => {
        this.camgkuList = response.data
      });
    },
    //获取所有商品
    getshangpin:function (){
      var obj={}
      obj.current = 1
      obj.size= 10000
      request({
        url: '/wh/products/page',
        method: 'get',
        params:obj
      }).then(response => {
        this.restaurants = response.data.records
        for (var i=0;i<this.restaurants.length;i++){
          this.restaurants[i].value =  this.restaurants[i].barCode
        }
      });
    },
    //添加
    addBtn:function (){
      this.addDialgData.inventoryLossInfoList.push(
        { goodsId:'',salesUnit:'',purchasePlanNumber:'',goodsSpecs:'',remark:'',atPresentCount:'',sumPrice:''},
      )
    },
    //获取下拉焦点
    focusBtn:function (index,row){
      focusXL(index)
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    handleSelect(item) {
      selectCG(item,this.addDialgData.inventoryLossInfoList)
      this.jisuanshuliang(this.addDialgData.inventoryLossInfoList)
    },
    //计算页面数据
    jisuanshuliang:function (ymArr){
      var sum=0
      for (var i=0;i<ymArr.length;i++){
        sum = sum+ ymArr[i].atPresentCount*1

      }
      this.addDialgData.inventoryLossCount = sum
    },
    handleIconClick(ev) {
      console.log('点击',ev);
      this.shangpinShow = true
    },
    //弹框回调
    callback:function (item){
      this.shangpinShow = false
      var arr= this.addDialgData.inventoryLossInfoList
      arr = arr.concat(item)
      this.addDialgData.inventoryLossInfoList = arr
      for(var i=0;i<this.addDialgData.inventoryLossInfoList.length;i++){
        if( this.addDialgData.inventoryLossInfoList[i].goodsId=='' || this.addDialgData.inventoryLossInfoList[i]=='' ){//解决初始化id为空导致多一条空数据
          this.addDialgData.inventoryLossInfoList.splice(i,1);
        }
      }
      this.addDialgData.inventoryLossInfoList = deteleObject(this.addDialgData.inventoryLossInfoList)
      this.jisuanshuliang(this.addDialgData.inventoryLossInfoList)

    },
    //删除采购单
    delBtn:function (){
      this.$confirm('此操作将删除采购单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //保存
    saveBtn:function (){

      if(!this.addDialgData.warehouseId){
        this.$message({
          type: 'warning',
          message:'盘点仓库不能为空！'
        });
        return
      }
      if(!this.addDialgData.crtTime){
        this.$message({
          type: 'warning',
          message:'单据日期不能为空！'
        });
        return
      }
      if(this.addDialgData.inventoryLossInfoList.length==0){
        this.$message({
          type: 'warning',
          message:'商品不能为空！'
        });
        return
      }
      for(var i=0;i<this.addDialgData.inventoryLossInfoList.length;i++){
        if(!this.addDialgData.inventoryLossInfoList[i].atPresentCount){
          this.$message({
            type: 'warning',
            message:'商品盘点数量不能为空！'
          });
          return
        }
        //盈亏数
        this.addDialgData.inventoryLossInfoList[i].profitAndLossCount = this.addDialgData.inventoryLossInfoList[i].atPresentCount*1-this.addDialgData.inventoryLossInfoList[i].inventory*1
        //盈亏成本
        this.addDialgData.inventoryLossInfoList[i].profitAndLossPrice =Math.round ((this.addDialgData.inventoryLossInfoList[i].atPresentCount*1-this.addDialgData.inventoryLossInfoList[i].inventory*1)*(this.addDialgData.inventoryLossInfoList[i].price*1)*100 )/ 100
      }

      if(this.addData.leixing=='put'){//修改
        request({
          url: '/wh/inventoryLoss/update',
          method: 'PUT',
          data:this.addDialgData
        }).then(response => {
          this.cancel();//隐藏
          if(response.code=='200'){
            this.$message({
              type: 'success',
              message:response.msg
            });
          }else {
            this.$message({
              type: 'warning',
              message:response.msg
            });
          }

        });
        return
      }
      //新增
      request({
        url: '/wh/inventoryLoss/add',
        method: 'post',
        data:this.addDialgData
      }).then(response => {
        this.cancel();//隐藏
        if(response.code=='200'){
          this.$message({
            type: 'success',
            message:response.msg
          });
        }else {
          this.$message({
            type: 'warning',
            message:response.msg
          });
        }

      });


    },
    //审核
    shBtn:function (){
      this.$confirm('此操作将审核通过, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.shenhe();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消审核'
        });
      });
    },
    //审核
    shenhe:function (){
      request({
        url: '/wh/inventoryLoss/audit?id='+this.addData.id,
        method: 'put',
      }).then(response => {
        if(response.code==200){
          this.$message({
            type: 'success',
            message:response.msg
          });
        }else {
          this.$message({
            type: 'warning',
            message:response.msg
          });
        }
        this.cancel();//隐藏
      });
    },
    //反审
    fsBtn:function (){
      this.$confirm('此操作将反审, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.bohui();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消反审'
        });
      });
    },
    //驳回
    bohui:function (){
      request({
        url: '/wh/inventoryLoss/rejected?id='+this.addData.id,
        method: 'put',
      }).then(response => {
        if(response.code==200){
          this.$message({
            type: 'success',
            message:response.msg
          });
        }else {
          this.$message({
            type: 'warning',
            message:response.msg
          });
        }
        this.cancel();//隐藏
      });
    },
    //删除
    handleDelete:function (index,row){
      this.addDialgData.inventoryLossInfoList.splice(index,1)
      this.jisuanshuliang(this.addDialgData.inventoryLossInfoList)
    },
    //确定
    determine:function(){

      this.$emit('callback','参书')//将submitModel的值传给父组件
    },
    //隐藏
    cancel:function(){
      // this.determine()
      this.$emit('callback','')//将submitModel的值传给父组件
    },

  }
};
</script>
<style scoped>
.addDialg {

}


</style>
